package com.flanz.apache.velocity.uimocker;

import java.io.File;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * class provides the startupconfiguration loaded in
 * {@link WebServer#start(ProjectConfig)}. object is designed as a singleton and
 * is available all over the application
 * 
 * @author hminst
 * 
 */
public class ConfigurationProvider {

	private static Logger LOG = LoggerFactory
			.getLogger(ConfigurationProvider.class);
	private static ConfigurationProvider singleton = null;
	private Configuration configuration;

	private ConfigurationProvider(final String configurationFile) {
		try {
			if (StringUtils.isEmpty(configurationFile)) {
				throw new ConfigurationException(
						"configuration is loaded the first time, but no configuration to laod from was passed!");
			}
			configuration = new PropertiesConfiguration(configurationFile);
		} catch (ConfigurationException e) {
			LOG.error("cannot load configuration!", e);
		}
		String projectDir = new File(".").getAbsolutePath();
		projectDir = StringUtils.removeEnd(projectDir, ".");

		// set the project's base directory if not configured
		if (StringUtils.isBlank(configuration.getString("project_dir"))) {
			configuration.setProperty("project_dir", projectDir);
			LOG.info("set project project_dir to {}", projectDir);
		}

	}

	/**
	 * @param configuration
	 *            when application is loaded the first time. when already
	 *            available null can be passed
	 * @return
	 */
	public static ConfigurationProvider getInstance(final String configuration) {
		if (singleton == null) {
			singleton = new ConfigurationProvider(configuration);
		}
		return singleton;
	}

	public Configuration getConfiguration() {
		return configuration;
	}

	public static String getProjectDir() {
		return getInstance(null).getConfiguration().getString("project_dir");
	}

	public static String getResourceDir() {
		return getInstance(null).getConfiguration().getString("resource_dir");
	}

}
